05. Quiz: Functional Interfaces

Why should you use the @FunctionalInterface annotation when writing your own functional interfaces?

SOLUTION:
  • It will cause a compilation error if the annotated interface is not a valid functional interface.
  • It tells users of your interface that the interface is intended to be targeted by lambdas.

@FunctionalInterface
public interface Function<T, R> {
    static <T> Function<T, T> identity() {
        return t -> t;
    }

    R apply(T t);

    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }

    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }
}

What is the functional method of the Function interface above?

SOLUTION: `apply`

abstract class Printable {
  abstract void print(String prefix);
}

Is Printable a functional interface?

SOLUTION: No

interface Squareable {
  default int square(int a) {
    return a * a;
  }
}

Is Squareable a functional interface?

SOLUTION: No

public interface BiFunction<T, U, R> {
  R apply(T t, U u);
}

Is BiFunction a functional interface?

SOLUTION: Yes

interface ConvertibleToString {
  @Override
  String toString();
}

Is ConvertibleToString a functional interface?

SOLUTION: No